package net.hn.hnms.biz.plan.service.impl;

import cn.hutool.core.util.StrUtil;
import com.baomidou.dynamic.datasource.annotation.DS;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import net.hn.hnms.biz.plan.domain.PlanOutput;
import net.hn.hnms.biz.plan.mapper.PlanOutputMapper;
import net.hn.hnms.biz.plan.request.PlanOutputReq;
import net.hn.hnms.biz.plan.service.IPlanOutputService;
import net.hn.hnms.biz.plan.vo.PlanOutputVO;
import net.hn.hnms.sys.common.core.constant.Constants;
import net.hn.hnms.sys.common.core.domain.ResponsePage;
import net.hn.hnms.sys.common.core.exception.HuaNengException;
import net.hn.hnms.sys.common.mybatis.core.page.PageQuery;
import net.hn.hnms.sys.system.api.RemoteUserService;
import net.hn.hnms.sys.system.api.model.LoginUser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;

/**
 * @author zhaoyang
 * 产量计划管理服务层实现
 * @date 2022-08-02
 */
@Service
@DS("master")
public class PlanOutputServiceImpl extends BaseService<PlanOutput, PlanOutputVO> implements IPlanOutputService {

    @Autowired
    private PlanOutputMapper planOutputMapper;
    @Autowired
    private RemoteUserService remoteUserService;
    /**
     * @param planOutput
     * @param pageQuery  查询产量计划列表
     */
    @Override
    public ResponsePage<PlanOutputVO> selectPageList(PlanOutputReq planOutput, PageQuery pageQuery) {

        Page<PlanOutput> page = planOutputMapper.selectPage(pageQuery.build(), buildQuery(planOutput).orderByDesc(PlanOutput::getOutputPlanCode).orderByDesc(PlanOutput::getCreateTime));
        List<PlanOutputVO> list = page.getRecords().stream().map(o -> convert(o, PlanOutputVO.class,o.getOutputPlanType())).collect(Collectors.toList());
        list.forEach(ii->{
            LoginUser userInfoById = remoteUserService.getUserInfoById(Long.valueOf(ii.getCreateUserId()));
            if (Optional.ofNullable(userInfoById).isPresent()) {
                ii.setCreateUserName(userInfoById.getNickname());
            }

        });
        return new ResponsePage<>(list, page.getTotal());
    }


    /**
     * 构造查询条件
     *
     * @param req
     * @return LambdaQueryWrapper<PlanDevelopment> 查询条件
     */
    private LambdaQueryWrapper<PlanOutput> buildQuery(PlanOutputReq req) {
        return new LambdaQueryWrapper<PlanOutput>()
                .like(StrUtil.isNotBlank(req.getOutputPlanCode()), PlanOutput::getOutputPlanCode, req.getOutputPlanCode())
                .like(StrUtil.isNotBlank(req.getOutputPlanName()), PlanOutput::getOutputPlanName, req.getOutputPlanName())
                .eq(StrUtil.isNotBlank(req.getOutputPlanType()), PlanOutput::getOutputPlanType, req.getOutputPlanType())
//                .eq(StrUtil.isNotBlank(req.getMineCode()), PlanOutput::getMineCode, req.getMineCode())
                .eq(StrUtil.isNotBlank(req.getStatus()), PlanOutput::getStatus, req.getStatus())
                .and(o->o.eq(req.getMineCode()!=null, PlanOutput::getMineCode, req.getMineCode()).or().eq(req.getCompanyCode()!=null, PlanOutput::getCompanyCode, req.getCompanyCode()));

    }

    /**
     * @param PlanOutput 查询掘进计划列表
     */
    @Override
    public List<PlanOutputVO> selectList(PlanOutputReq PlanOutput) {
        List<PlanOutput> list = planOutputMapper.selectList(buildQuery(PlanOutput));
        return list.stream().map(o -> convert(o, PlanOutputVO.class,o.getOutputPlanType())).collect(Collectors.toList());
    }

    /**
     * @param planOutput 新增产量计划
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public int insert(PlanOutputReq planOutput) {

        PlanOutput insertObj = new PlanOutput();
        copyProperties(planOutput, insertObj, planOutput.getOutputPlanType());
        //自动生成 计划名称 计划编号
        insertObj.setOutputPlanName(generatePlanName(planOutput.getOutputPlanType(),insertObj.getPlanStartDate()));
        insertObj.setOutputPlanCode(generatePlanCode(planOutput.getOutputPlanType(),insertObj.getPlanStartDate()));
        insertObj.setStatus("0");
        QueryWrapper<PlanOutput> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("output_plan_code", insertObj.getOutputPlanCode());
        if (planOutputMapper.selectCount(queryWrapper) > 0) {
            throw new HuaNengException(Constants.FAIL, "已存在同一时段的计划");
        }
        return planOutputMapper.insert(insertObj);
    }

    /**
     * @param idList 批量删除
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deleteBatch(List<String> idList) {
        planOutputMapper.deleteBatchIds(idList);
    }

    /**
     * @param planOutput 单个修改 按照主键修改信息
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updateById(PlanOutputReq planOutput) {
        if (StrUtil.isBlank(planOutput.getOutputPlanId())) {
            throw new HuaNengException(Constants.FAIL, "id不能为空");
        }
        PlanOutput updateObj = new PlanOutput();
        copyProperties(planOutput, updateObj, planOutput.getOutputPlanType());
        updateObj.setOutputPlanName(generatePlanName(planOutput.getOutputPlanType(),updateObj.getPlanStartDate()));
        updateObj.setOutputPlanCode(generatePlanCode(planOutput.getOutputPlanType(),updateObj.getPlanStartDate()));
        QueryWrapper<PlanOutput> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("output_plan_code", updateObj.getOutputPlanCode());
        queryWrapper.ne("output_plan_id", updateObj.getOutputPlanId());
        if (planOutputMapper.selectCount(queryWrapper) > 0) {
            throw new HuaNengException(Constants.FAIL, "已存在同一时段的计划");
        }
        int updateCount = planOutputMapper.updateById(updateObj);
        if (updateCount == 0) {
            throw new HuaNengException(Constants.FAIL, "数据不存在");
        }
    }

    /**
     * @param id 按主键id查询详情
     */
    @Override
    public PlanOutputVO selectDetailById(String id) {
        PlanOutput output = planOutputMapper.selectById(id);
        if (output == null) {
            throw new HuaNengException(Constants.FAIL, "数据不存在");
        }
        return convertWithUser(output, PlanOutputVO.class);
    }

    /**
     * 启用/禁用
     * @param id 数据id
     * @param status  status: 0:启用 1:禁用
     */
    public void changeStatus(String id, Integer status) {
        if (status == 1 || status == 0) {
            PlanOutput planMining = planOutputMapper.selectById(id);
            if (planMining == null) {
                throw new HuaNengException(Constants.FAIL, "数据不存在");
            }
            planMining.setStatus(status + "");
            int res = planOutputMapper.updateById(planMining);
            if (res == 0) {
                throw new HuaNengException(Constants.FAIL, "数据不存在");
            }
            return;
        }
        throw new HuaNengException(Constants.FAIL, "传入的参数错误");
    }
}
